<template>
  <div>
    <div v-if="row.actions.length>2">
      <a @click="handleClickMore(row.actions[0].name, row)"
         v-if="showBtn(row.actions[0].label)">{{ row.actions ? row.actions[0].label : '' }}</a>
      <Divider type="vertical" />
      <Dropdown @on-click="(name) => handleClickMore(name, row)"
                transfer>
        <a>更多
          <Icon type="ios-arrow-down" />
        </a>
        <DropdownMenu slot="list">
          <template v-for="(item, i) in row.actions.slice(1)">
            <DropdownItem v-if="showBtn(item.label)"
                          :key="i"
                          :name="item.name">{{ item.label }}
            </DropdownItem>
          </template>

        </DropdownMenu>
      </Dropdown>
    </div>
    <div v-else>
      <a v-if="row.actions"
         @click="handleClickMore(row.actions[0].name, row)">{{ row.actions[0].label }}</a>
      <Divider v-if="row.actions && row.actions.length>1"
               type="vertical" />
      <a v-if="row.actions && row.actions.length>1"
         @click="handleClickMore(row.actions[1].name, row)">{{ row.actions[1].label }}</a>
    </div>
    <Modal v-model="showProp"
           title="关联商品"
           width="800"
           :fullscreen="true">
      <Row type="flex">
        <Col span="8">SPU编码：<Input v-model="spuNo"
               placeholder="请输入内容"
               style="width: 200px" /></Col>
        <Col span="8">商品名称：<Input v-model="productName"
               placeholder="请输入内容"
               style="width: 200px" /></Col>
        <Col span="8">
        <Button type="primary"
                @click="linkSearch">查询</Button>
        <Button style="margin-left: 8px;"
                @click="linkSearch('clear')">清空</Button>
        </Col>
      </Row>
      <div style="position: absolute;top: 57px;right: 30px;z-index: 9;">
        <Button v-if="relationType=='noRelation'"
                type="info"
                @click="toRelation('all')">批量关联</Button>
        <Button v-if="relationType=='isRelation'"
                type="info"
                @click="closeRelation('all')">批量取消</Button>
      </div>
      <Row>
        <Tabs @on-click="tabsChang"
              style="margin: 10px;">
          <TabPane label="未关联"
                   name="noRelation">
            <Table :columns="linkCol"
                   :data="linkData"
                   @on-select="handleBaseTablaeSelect($event,'1')"
                   @on-select-all="handleSelectAll($event,'1')"
                   @on-select-all-cancel="handleSelectAllCancel($event,'1')">
              <template slot-scope="{ row, index }"
                        slot="action">
                <Button type="success"
                        size="small"
                        style="margin:3px 0"
                        @click="toRelation('',row.skuNo)">关联</Button>
              </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
              <Page :total="totalNum"
                    show-total
                    show-sizer
                    :current.sync="nowPage"
                    @on-change="getProductList('noRelation')"
                    @on-page-size-change="handleChangePage" />
            </div>
          </TabPane>
          <TabPane label="已关联"
                   name="isRelation">
            <Table :columns="linkCol"
                   :data="linkData"
                   @on-select="handleBaseTablaeSelect($event,'2')"
                   @on-select-all="handleSelectAll($event,'2')"
                   @on-select-all-cancel="handleSelectAllCancel($event,'2')">
              <template slot-scope="{ row, index }"
                        slot="action">
                <Button type="success"
                        size="small"
                        style="margin:3px 0"
                        @click="closeRelation('',row.skuNo)">取消</Button>
              </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
              <Page :total="totalNum"
                    show-total
                    show-sizer
                    :current.sync="nowPage"
                    @on-change="getProductList('isRelation')"
                    @on-page-size-change="handleChangePage" />
            </div>
          </TabPane>
        </Tabs>
      </Row>
    </Modal>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import dynamictableactions from '@/mixins/dynamictableactions'; // 混入通用代码
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission'
export default {
  mixins: [
    dynamictableactions
  ],
  data () {
    return {
      actions: [],
      linkCol: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '商品名称',
          key: 'productName',
          minWidth: 150
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          minWidth: 150
        },
        {
          title: '商品分类',
          key: 'categoryPath',
          minWidth: 150
        },
        {
          title: '管理区域',
          key: 'manageArea',
          minWidth: 150
        },
        {
          title: '规格参数',
          key: 'saleAttrInfo',
          minWidth: 150
        },
        {
          title: '品牌',
          key: 'brandName',
          minWidth: 150
        },
        {
          title: '操作',
          slot: 'action',
          width: 150,
          align: 'center'
        }
      ],
      linkData: [], // 商品数据信息
      relationType: 'noRelation', //当前选择的关联类型 未关联noRelation
      showProp: false, // 是否展示关联商品弹出框
      totalNum: 0, // 总条数
      nowPage: 1, // 当前页数
      pageShow: 10, // 每页展示条数
      skuNoList: [], // 选择的商品uuid数组
      productName: '', // 商品名称
      spuNo: '', // 商品spu编号
      uuid: '' // 当前选择的要关联商品的知识点
    }
  },
  created () {
  },
  computed: {
    ...mapGetters('permissions/systemBtns', [
      'showBtn'
    ]),
  },
  methods: {
    // 切换已关联未关联
    tabsChang (name) {
      this.relationType = name;
      this.nowPage = 1;
      this.skuNoList = [];
      this.linkData = [];
      this.getProductList()
    },
    // 商品信息查询
    linkSearch (type = '') {
      if (type == 'clear') { // 清空
        this.productName = '';
        this.spuNo = '';
      }
      this.getProductList()
    },
    // 获取未关联和未关联商品信息
    getProductList () {
      let type = this.relationType;
      let searchParam = [];
      if (this.spuNo !== '') {
        this.spuNo = this.spuNo.replace(/ /g, '')  //过滤掉空格
      }
      if (this.productName !== '') {
        this.productName = this.productName.replace(/ /g, '')
      }


      searchParam.push({ name: 'productName', value: this.productName });
      searchParam.push({ name: 'productName_q', value: 'Like' });
      searchParam.push({ name: 'spuNo', value: this.spuNo });
      searchParam.push({ name: 'spuNo_q', value: 'Like' });
      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        searchParam: JSON.stringify(searchParam),
        sortName: '',
        sortType: ''
      }
      let requerUrl = ''
      if (type == 'noRelation') { // 未关联
        requerUrl = '/sysback/knowledgebaseskurel/getNotRelByCondition?knowledgeUuid=' + this.uuid
      }
      if (type == 'isRelation') { // 已关联
        requerUrl = '/sysback/knowledgebaseskurel/getRelByCondition?knowledgeUuid=' + this.uuid
      }
      ApiRequest(requerUrl, 'post', data, false).then(res => {
        if (res.retStatus === '1') {
          this.linkData = res.retData.results;
          this.totalNum = res.retData.totalNum;
        }
      })
    },
    //全选
    handleSelectAll (row, type) {
      this.skuNoList = [];
      if (type === '1') {
        row.forEach(element => {
          this.skuNoList.push(element.skuNo);
        });
      } else {
        row.forEach(element => {
          this.skuNoList.push(element.skuNo);
        });
      }

    },
    //取消全选
    handleSelectAllCancel () {
      this.skuNoList = [];
    },
    //单独选择操作
    handleBaseTablaeSelect (row, type) {
      this.skuNoList = [];
      if (type === '1') {
        row.forEach(element => {
          this.skuNoList.push(element.skuNo);
        });
      } else {
        row.forEach(element => {
          this.skuNoList.push(element.skuNo);
        });
      }
    },
    // 分页
    handleChangePage (val) {
      this.pageShow = val
      this.$nextTick(() => {
        this.getProductList()
      })
    },
    // 关联商品
    toRelation (type = '', skuNo = '') {
      let skuNos = '';
      if (type == 'all') { // 批量关联
        if (this.skuNoList && this.skuNoList.length > 0) {
          skuNos = this.skuNoList.join(',')
        } else {
          this.$Message.warning('请选择要关联的商品')
          return
        }

      } else { // 单个关联
        skuNos = skuNo;
      }
      let data = {
        knowledgeUuid: this.uuid,
        skuNos: skuNos
      }
      ApiRequest('/sysback/knowledgebaseskurel/createRelate', 'post', data, true).then(res => {
        if (res.retStatus === '1') {
          this.getProductList();
        }
      })
    },
    // 取消关联
    closeRelation (type = '', skuNo = '') {
      let skuNos = '';
      if (type == 'all') { // 批量关联
        if (this.skuNoList && this.skuNoList.length > 0) {
          skuNos = this.skuNoList.join(',')
        } else {
          this.$Message.warning('请选择要取消关联的商品')
          return
        }
      } else { // 单个关联
        skuNos = skuNo;
      }
      let data = {
        knowledgeUuid: this.uuid,
        skuNos: skuNos
      }
      ApiRequest('/sysback/knowledgebaseskurel/deleteRelate', 'post', data, true).then(res => {
        if (res.retStatus === '1') {
          this.getProductList();
        }
      })
    },
    // 知识点列表批量操作
    handleClickMore (name, row) {
      if (name === 'Delete') {
        this.$Modal.confirm({
          title: '删除操作',
          content: '确定删除此数据吗？',
          onOk: () => {
            let curBtnId = getBtnsId('删除')
            sessionStorage.setItem('buttonId', curBtnId)
            let data = {
              uuid: row.uuid
            }
            // 开始请求商品列表
            ApiRequest(this.requestApi.delTableList.url, this.requestApi.delTableList.type, data, true).then(res => {
              if (res.retStatus == '1') {
                this.$Message.success('删除成功')
                this.actionsChange()
              }
            })
          }
        })
      } else {
        let obj = {} // 动作的对象信息
        row.actions.forEach(item => {
          if (name === item.name) {
            obj = item
            return false
          }
        })
        this.setTableRowData(row)
        if (obj.handleType === 'View' || obj.handleType === 'Edit') {
          let curBtnId = getBtnsId('编辑')
          sessionStorage.setItem('buttonId', curBtnId)
          // 操作类型为链接时，拼接参数跳转
          let jumpPath = this.jumpPath + obj.name;
          this.$router.push({ path: jumpPath, query: { uuid: row.uuid } })
        } else {
          let curBtnId = getBtnsId('关联商品')
          sessionStorage.setItem('buttonId', curBtnId)
          // 操作类型为弹窗时 打开弹窗
          this.uuid = row.uuid;
          this.showProp = true;
          this.getProductList()
        }
      }
    }
  }

}
</script>
